import { lazy, ComponentType, } from "react"
import Home from "@/views/Home"
import withLoadingComponent from "@/components/withLoadingComponent"  // 封装一个Loading组件
// import { Navigate } from "react-router-dom"
import Error404 from '@/components/error404'
import Login from '@/views/login'
/**
 * 根据 views 目录生成路径配置
 */

const GENERATE_PATH_CONFIG = ():object[] => {
    // 扫描 src/views 下的所有具有路由文件
    const MODULES = import.meta.glob<{default: ComponentType}>('/src/views/**/*.tsx');
    const AUTO_LOAD_ROUTES: object[] = [];

    Object.keys(MODULES).forEach((filePath) => {
      const path = filePath
        // 去除 src/pages 不相关的字符
        .replace('/src/views', '')
        // 去除文件名后缀
        .replace(/.tsx?/, '')

        AUTO_LOAD_ROUTES.push({ path,element:WRAP_SUSPENSE(MODULES[filePath]) })
    });
    return AUTO_LOAD_ROUTES;
}

/**
 * 为动态 import 包裹 lazy 和 Suspense
 */
const WRAP_SUSPENSE = (importer: () => Promise<{ default: ComponentType }>) => {
    if (!importer) undefined 

    // 使用 React.lazy 包裹 () => import() 语法
    const COMPONENT = lazy(importer);
    // 结合 Suspense，这里可以自定义 loading 组件
    return withLoadingComponent( <COMPONENT /> );
}


const ROUTES = [
    //   "/" 第一个为重定向
    {
        path: "/",
        // element: <Navigate to="/test1/index"/>
        element: <Login />
    },
    {
        path: "/",
        element: <Home />,
        children: [
            ...GENERATE_PATH_CONFIG(),
        ],
    },
    
    // 访问其余路径的时候直接跳到404
    {
        path: "*",
        element: <Error404 />
    }
]

export default ROUTES